package com.jier.controller.console;

import com.jier.annotation.ValidateField;
import com.jier.annotation.ValidateGroup;
import com.jier.common.Result;
import com.jier.common.exception.HttpParamException;
import com.jier.common.permission.Permission;
import com.jier.controller.BaseController;
import com.jier.dto.SystemRolePermissionResultDto;
import com.jier.entities.SystemModule;
import com.jier.entities.SystemRole;
import com.jier.enums.RoleType;
import com.jier.model.PageParam;
import com.jier.service.ISystemModuleService;
import com.jier.service.ISystemPermissionService;
import com.jier.service.ISystemRolePermissionService;
import com.jier.service.ISystemRoleService;
import com.jier.vo.admin.FieldVo;
import com.jier.vo.admin.SystemPermissionModuleVo;
import com.jier.vo.admin.SystemRolePermissionVo;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 系统角色控制器
 *
 * @author jie_r
 * @date 2018/03/08
 */
@RestController
@RequestMapping("/console/systemRoles")
public class SystemRoleController extends BaseController {
    @Autowired
    private ISystemRoleService systemRoleService;
    @Autowired
    private ISystemPermissionService systemPermissionService;
    @Autowired
    private ISystemModuleService systemModuleService;
    @Autowired
    private ISystemRolePermissionService systemRolePermissionService;

    /**
     * 系统角色首页-管理页面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/index.html", method = RequestMethod.GET)
    @ApiOperation(value = "系统角色首页-管理页面", hidden = true, httpMethod = "GET")
    @Permission(code = "010201", content = "系统角色首页-管理页面")
    public ModelAndView index() throws Exception {
        return new ModelAndView("/systemRole/systemRoles");
    }

    /**
     * 添加系统角色-管理页面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/add.html", method = RequestMethod.GET)
    @ApiOperation(value = "添加系统角色-管理页面", hidden = true, httpMethod = "GET")
    @Permission(code = "010202", content = "添加系统角色-管理页面")
    public ModelAndView addPage() throws Exception {
        return new ModelAndView("/systemRole/add_systemRole");
    }

    /**
     * 编辑系统用户-管理页面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/edit.html", method = RequestMethod.GET)
    @ApiOperation(value = "编辑系统角色-管理页面", hidden = true, httpMethod = "GET")
    @Permission(code = "010203", content = "编辑系统角色-管理页面")
    public ModelAndView editPage(Integer id) throws Exception {
        ModelAndView mv = new ModelAndView("/systemRole/edit_systemRole");
        SystemRole systemRole = systemRoleService.getById(id);
        mv.addObject("systemRole", systemRole);
        return mv;
    }

    /**
     * 编辑系统角色权限-管理页面
     *
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/editPermission.html", method = RequestMethod.GET)
    @ApiOperation(value = "编辑系统角色权限-管理页面", hidden = true, httpMethod = "GET")
    @Permission(code = "010203", content = "编辑系统角色权限-管理页面")
    public ModelAndView editPermissionPage(Integer id) throws Exception {
        ModelAndView mv = new ModelAndView("/systemRole/edit_systemRolePermission");
        // 获取二级模块
        List<SystemModule> systemModules = systemModuleService.getSecondLevelNaves();
        List<SystemPermissionModuleVo> systemPermissionModules = systemModules.stream().map(systemModule -> new SystemPermissionModuleVo(systemModule.getName())).collect(Collectors.toList());
        List<SystemRolePermissionResultDto> systemRolePermissions = systemPermissionService.getSystemPermissionByRoleId(id);
        for (SystemPermissionModuleVo systemPermissionModule : systemPermissionModules) {
            for (SystemRolePermissionResultDto systemRolePermission : systemRolePermissions) {
                if (systemPermissionModule.getName().equals(systemRolePermission.getModuleName())) {
                    systemPermissionModule.getPermissions().add(new SystemRolePermissionVo(systemRolePermission));
                }
            }
        }
        mv.addObject("systemPermissionModules", systemPermissionModules);
        mv.addObject("roleId", id);
        return mv;
    }


    /**
     * 获取系统角色
     *
     * @param pageParam
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "", method = RequestMethod.GET, produces = "application/json;")
    @ApiOperation(value = "获取系统角色", httpMethod = "GET", produces = "application/json;")
    @Permission(code = "010201", content = "获取系统角色")
    public ResponseEntity<Result<SystemRole>> getSystemUsers(PageParam pageParam) throws Exception {
        Result<SystemRole> result = systemRoleService.getSystemRoles(getPage(pageParam));
        return ok(result);
    }

    /**
     * 添加系统角色
     *
     * @param name
     * @param status
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "", method = RequestMethod.POST, produces = "application/json;")
    @ApiOperation(value = "添加系统角色", httpMethod = "POST", produces = "application/json;")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "名字", dataType = "String", required = true),
            @ApiImplicitParam(name = "status", value = "状态", dataType = "Boolean", required = true)
    })
    @ValidateGroup(fields = {
            @ValidateField(index = 0, paramName = "名字", notNull = true, maxLen = 15),
            @ValidateField(index = 1, paramName = "状态", notNull = true)
    })
    @Permission(code = "010202", content = "添加系统角色")
    public ResponseEntity<Boolean> addSystemRole(String name, Boolean status) throws Exception {
        SystemRole systemRole = systemRoleService.getSystemRoleByName(name);
        if (systemRole != null) {
            throw new HttpParamException("系统角色【" + name + "】不存在");
        }
        systemRole = new SystemRole();
        systemRole.setName(name);
        systemRole.setType(RoleType.normalAdmin.ordinal());
        systemRole.setStatus(status);
        systemRole.setUpdateDate(new Date());
        systemRole.setCreateDate(new Date());
        systemRoleService.save(systemRole);
        return ok(Boolean.TRUE);
    }

    /**
     * 编辑系统角色
     *
     * @param name
     * @param status
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.POST, produces = "application/json;")
    @ApiOperation(value = "编辑系统角色", httpMethod = "POST", produces = "application/json;")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "名字", dataType = "String", required = true),
            @ApiImplicitParam(name = "status", value = "状态", dataType = "Boolean", required = true),
            @ApiImplicitParam(name = "id", value = "系统角色ID", dataType = "Integer", required = true)
    })
    @ValidateGroup(fields = {
            @ValidateField(index = 0, paramName = "名字", notNull = true, maxLen = 15),
            @ValidateField(index = 1, paramName = "状态", notNull = true)
    })
    @Permission(code = "010203", content = "编辑系统角色")
    public ResponseEntity<Boolean> updateSystemRole(String name, Boolean status, @PathVariable Integer id) throws Exception {
        SystemRole systemRole = systemRoleService.getById(id);
        if (systemRole == null) {
            throw new HttpParamException("系统角色不存在");
        }
        systemRole.setName(name);
        systemRole.setStatus(status);
        systemRoleService.updateById(systemRole);
        return ok(Boolean.TRUE);
    }

    /**
     * 获取所有系统角色
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/all", method = RequestMethod.GET, produces = "application/json;")
    @ApiOperation(value = "获取所有系统角色", httpMethod = "GET", produces = "application/json;")
    public ResponseEntity<List<FieldVo>> getAll() throws Exception {
        List<SystemRole> systemRoles = systemRoleService.getSystemRoles();
        List<FieldVo> fieldVoes = new ArrayList<>();
        for (SystemRole systemRole : systemRoles) {
            FieldVo fieldVo = new FieldVo();
            fieldVo.setId(systemRole.getId());
            fieldVo.setName(systemRole.getName());
            fieldVoes.add(fieldVo);
        }
        return ok(fieldVoes);
    }

    /**
     * 编辑系统角色权限
     *
     * @param permissionIds
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/{id}/permission", method = RequestMethod.POST, produces = "application/json;")
    @ApiOperation(value = "编辑系统角色权限", httpMethod = "POST", produces = "application/json;")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "permissionId", value = "权限ID集", dataType = "Integer", required = true)
    })
    @Permission(code = "010203", content = "编辑系统角色权限")
    public ResponseEntity<Boolean> updateSystemRolePermission(@RequestParam(value = "permissionId", required = false) List<Integer> permissionIds, @PathVariable Integer id) throws Exception {
        SystemRole systemRole = systemRoleService.getById(id);
        if (systemRole == null) {
            throw new HttpParamException("系统角色不存在");
        }
        systemRolePermissionService.updateSystemRolePermission(id, permissionIds);
        return ok(Boolean.TRUE);
    }
}
